<template>
  <a-form layout="vertical" class="login-form">
    <a-form-item label="账户" name="account">
      <a-input v-model:value="loginForm.account" placeholder="请输入注册账户" allow-clear>
        <template #prefix>
          <IdcardOutlined />
        </template>
      </a-input>
    </a-form-item>

    <a-form-item label="密码" name="password">
      <a-input-password v-model:value="loginForm.password" placeholder="请输入密码" allow-clear>
        <template #prefix>
          <LockOutlined />
        </template>
      </a-input-password>
    </a-form-item>

    <a-form-item>
      <a-button type="primary" @click="handleLogin" html-type="submit" block :loading="loading" class="login-btn">
        立即登录
      </a-button>
    </a-form-item>
  </a-form>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { message } from 'ant-design-vue';
import { useRouter } from 'vue-router';
import { useAuthStore } from '../store/auth';
import { IdcardOutlined, LockOutlined } from '@ant-design/icons-vue';
import axios from '../utils/axios';

const router = useRouter();
const loading = ref(false);

const loginForm = ref({
  account: '',
  password: ''
});

const handleLogin = async () => {
  try {
    loading.value = true;
    const { data } = await axios.post('/users/login', loginForm.value);

    const authStore = useAuthStore();
    await authStore.loginSuccess(data.token);
    message.success('登录成功');

    // 获取完整用户信息
    const profile = await axios.get('/users/profile');
    localStorage.setItem('user', JSON.stringify(profile.data.data));

    router.replace('/welcome');
  } catch (error: any) {
    console.error('[登录错误]', error);
    const status = error.response?.status;
    let errMsg = '网络连接异常，请稍后重试';

    if (status === 400) errMsg = '请求参数错误';
    if (status === 401) errMsg = '账户或密码错误';
    if (status === 500) errMsg = '服务器内部错误';

    message.error(errMsg);
    loginForm.value.password = '';
  }
};
</script>

<style scoped>
.login-form {
  max-width: 400px;
  margin: 0 auto;
  padding: 20px;
}

.login-btn {
  margin-top: 24px;
  height: 40px;
}
</style>
